import axios from "axios";
import { getToken } from "./setCookie.js";
import { Dialog } from "vant";
const instance = axios.create({
  baseURL: "http://localhost:3009",
  timeout: 5000,
  headers: {},
});
// 请求拦截
instance.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.authorization = `Bearer ${getToken()}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
// 响应拦截
instance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    const { response } = error;
    const { status } = response;
    if (status === 401) {
      Dialog.confirm({
        message: "您还没有登录，是否去登录",
      })
        .then(() => {
          location.href = "#/login";
        })
        .catch(() => {
          // on cancel
        });
    }
    return Promise.reject(error);
  }
);

// 封装get请求  axios.get(url,{params:params})
export const get = (url, params) => instance.get(url, { params });
// 封装post请求  axios.post(url,{name:'张三'，age:20})
export const post = (url, data) => instance.post(url, data);

// 封装删除接口
export const dele = (url, params) => instance.delete(url, { params });
// 封装put 请求
export const put = (url, data) => instance.put(url, data);
export default instance;
